package bservice

import (
    "fmt"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    "gonaio_base/constant"
    "sync"
)

var dbMap sync.Map

func (that Service) GetDB(name string) (db *gorm.DB, err error) {
    if name == "" {
        name = bconstant.THE_MYSQL_DEFAULT
    }
    value, ok := dbMap.Load(name)
    if ok {
        db = value.(*gorm.DB)
        return
    }
    dns, err := that.getDns(name)
    if err != nil {
        return
    }
    db, err = that.getDatabase(dns)
    if err != nil {
        return
    }
    dbMap.Store(name, db)
    return
}

func (Service) ClearDB() {
    dbMap = sync.Map{}
}

func (that Service) getDns(name string) (dns string, err error) {
    h, err := that.GetConfigHandle()
    if err != nil {
        return
    }
    host := string(h.Get(bconstant.THE_DEFAULT, "mysql", name, "host").Bytes())
    port := string(h.Get(bconstant.THE_DEFAULT, "mysql", name, "port").Bytes())
    username := string(h.Get(bconstant.THE_DEFAULT, "mysql", name, "username").Bytes())
    password := string(h.Get(bconstant.THE_DEFAULT, "mysql", name, "password").Bytes())
    database := string(h.Get(bconstant.THE_DEFAULT, "mysql", name, "database").Bytes())
    charset := string(h.Get(bconstant.THE_DEFAULT, "mysql", name, "charset").Bytes())
    loc := string(h.Get(bconstant.THE_DEFAULT, "mysql", name, "loc").Bytes())
    dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s", username, password, host, port, database, charset, loc)
    return
}

func (Service) getDatabase(dns string) (db *gorm.DB, err error) {
    db, err = gorm.Open("mysql", dns)
    return
}
